// src/utils/websocket.js
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

let stompClient = null;

export function connectWebSocket(userId, { onOpen, onMessage, onClose, onError }) {
  const socket = new SockJS('http://localhost:8080/ws');
  stompClient = Stomp.over(socket);

  stompClient.connect({}, (frame) => {
      console.log('Stomp 连接成功，frame:', frame); // 添加这行调试信息
      if (onOpen) {
          console.log('准备调用 onOpen 回调'); // 添加这行调试信息
          onOpen();
          console.log('onOpen 回调调用完毕'); // 添加这行调试信息
      }

      const subscriptionPath = `/user/${userId}/queue/notifications`;
      console.log('订阅路径: ', subscriptionPath);
      stompClient.subscribe(subscriptionPath, (message) => {
        console.log('收到消息:', message);
          try {
              const content = JSON.parse(message.body);
              if (onMessage) {
                  onMessage(content);
              }
          } catch (error) {
              console.error('解析消息时出错:', error);
          }
      });
  }, (error) => {
      if (onError) {
          onError(error);
      }
      console.error('WebSocket连接失败:', error);
  });
}

export function disconnectWebSocket() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
}
